package controllers

import (
	"2302a-rk10/models"
	beego "github.com/beego/beego/v2/server/web"
)

type ShopController struct {
	beego.Controller
}
type Msg struct {
	Msg  string
	Code int
	Data interface{}
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	kg, _ := c.GetFloat("kg")
	num, _ := c.GetInt("num")
	shop := models.Shop{
		Name:  name,
		Kg:    kg,
		Num:   num,
		Price: price,
	}
	if shop.Name == "" || shop.Price == 0 || shop.Kg == 0 || shop.Num == 0 {
		res := Msg{
			Msg:  "格式不能为空",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
	err := models.DB.Debug().Create(&shop).Error
	if err != nil {
		res := Msg{
			Msg:  "添加失败",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Msg:  "添加成功",
			Code: 200,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	var allshop []models.Shop
	err := models.DB.Debug().Find(&allshop).Error
	if err != nil {
		res := Msg{
			Msg:  "查询失败",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Msg:  "查询成功",
			Code: 200,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *ShopController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	kg, _ := c.GetFloat("kg")
	num, _ := c.GetInt("num")
	shop := models.Shop{
		Name:  name,
		Price: price,
		Kg:    kg,
		Num:   num,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&shop).Error
	if err != nil {
		res := Msg{
			Msg:  "修改失败",
			Code: 0,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Msg:  "修改成功",
			Code: 200,
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
